const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const  cors = require('koa2-cors')
const index = require('./routes/index')
// error handler
onerror(app)

// middlewares
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(cors())
app.use(json())
app.use(logger())


// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})
// 404 500
app.use(async (ctx, next) => {
    try {
        await next()
    } catch (error) {
        console.log(error)
        ctx.body = { code: -1000, message: '服务器内部错误' }
    }
    // console.log(ctx.status)
    if (ctx.status === 404 || ctx.status === 405) ctx.body = { code: -100, message: '无效的api请求'}
})
// routes
app.use(index.routes(), index.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
